#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt5.QtCore import Qt,QDate,QDateTime,QTime
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtSql import  QSqlRelationalDelegate

from forms.toFuelRecords import Ui_ToFuelRecordForm
from delegates import  DateDelegate

import dbUtil
from tables import *


class ToFuelRecordForm(QWidget,Ui_ToFuelRecordForm):
    def __init__(self):
        super(ToFuelRecordForm, self).__init__()
        
        # Set up the user interface from Designer.
        self.setupUi(self)
        self.btnAdd.clicked.connect(self.addRecord)
        self.btnDel.clicked.connect(self.delRecord)
        self.btnOk.clicked.connect(self.submit)
        self.btnCancel.clicked.connect(self.cancel)
        self.tvRecords.setModel(dbUtil.getToFuelRecModel())
        self.tvRecords.setItemDelegate(QSqlRelationalDelegate(self.tvRecords))
        self.tvRecords.setColumnHidden(0,True)
        self.tvRecords.setColumnHidden(TC_TF_VEHICLE,True)
        self.tvRecords.model().dataChanged.connect(self.recordDataChanged)
        self.cmbVehicleNumber.currentIndexChanged.connect(self.vehicleChanged)
        self.cmbYear.currentTextChanged.connect(self.yearChanged)

        self.cmbVehicleNumber.setModel(dbUtil.getVehicleModel())
        self.cmbVehicleNumber.setModelColumn(TC_TF_VEHICLE)

        self.delegate = DateDelegate(TC_TF_DATE)
        self.tvRecords.setItemDelegateForColumn(TC_TF_DATE,self.delegate)

    def setRecModel(self,model):
        self.tvRecords.setModel(model)
        model.select()

    def vehicleChanged(self,vIndex):
        self.cmbYear.clear()
        m = self.cmbVehicleNumber.model()
        vId = m.data(m.index(self.cmbVehicleNumber.currentIndex(),0))
        si,ei=dbUtil.getYearScope(vId)
        if(si!=0 and ei!=0):
            sy = QDateTime.fromMSecsSinceEpoch(si).date().year()
            ey = QDateTime.fromMSecsSinceEpoch(ei).date().year()
            for y in range(sy,ey+1):
                self.cmbYear.addItem(str(y))
            self.cmbYear.setCurrentIndex(ey-sy)
        else:
            self.filterRecords()

    def yearChanged(self,year):
        if(year==''):
            return
        self.filterRecords()

    def submit(self):
        if(self.tvRecords.model().isDirty()):
            self.tvRecords.model().submitAll()
        #self.close()


    def cancel(self):
        if(self.tvRecords.model().isDirty()):
            self.tvRecords.model().revertAll()
        #self.close()

    def addRecord(self):
        m=self.tvRecords.model()
        row=m.rowCount()
        m.insertRow(row)
        mv = self.cmbVehicleNumber.model()
        vId = mv.data(m.index(self.cmbVehicleNumber.currentIndex(),0)) #设置车辆
        fId = dbUtil.getFuelForVehicle(vId)
        self.tvRecords.model().dataChanged.disconnect(self.recordDataChanged)
        m.setData(m.index(row,TC_TF_VEHICLE),vId)
        m.setData(m.index(row,TC_TF_FUEL),fId)   #设置与车辆适配的燃料
        stationId = dbUtil.getPreferredStation()
        if(stationId):
            m.setData(m.index(row,TC_TF_STATION),stationId)
        self.tvRecords.model().dataChanged.connect(self.recordDataChanged)
        m.setData(m.index(row,TC_TF_DATE),QDateTime.currentDateTime().toMSecsSinceEpoch()) #默认为当前日期
        self.tvRecords.scrollToBottom()


    def recordDataChanged(self,topLeft, bottomRight, roles = list()):
        col = topLeft.column()
        row = topLeft.row()
        m = self.tvRecords.model()
        if(col == TC_TF_DATE or col == TC_TF_FUEL):   #只对日期和燃料的改变
            fuel = m.data(m.index(row,TC_TF_FUEL),Qt.EditRole)
            if(not fuel):
                return
            date = m.data(m.index(row,TC_TF_DATE))
            prices = dbUtil.getPriceForDate(QDateTime(QDate.fromString(date,Qt.ISODate)).toMSecsSinceEpoch(),True)
            price=0.0
            if(fuel in prices):
                price = prices[fuel]
            if(price != 0):
                m.setData(m.index(row,TC_TF_PRICE),price)
        elif(col == TC_TF_MONEY or col == TC_TF_PRICE): #如果金额或单价改变，则自动计算加油数量
            money = m.data(m.index(row,TC_TF_MONEY))
            if(money==0):
                return
            price = m.data(m.index(row,TC_TF_PRICE))
            if(price == 0):
                return
            amount = money/price
            m.setData(m.index(row,TC_TF_AMOUNT),amount)

    def delRecord(self):
        rowIndex = self.tvRecords.selectionModel().selectedRows()
        if(not rowIndex):
            return
        if(QMessageBox.question(self,"提醒信息","确定要删除所选的加油记录？",QMessageBox.Yes|QMessageBox.No) == QMessageBox.No):
            return
        for index in rowIndex:
            r = index.row()
            self.tvRecords.model().removeRow(r)
        self.tvRecords.model().submitAll()

    def filterRecords(self):
        m = self.cmbVehicleNumber.model()
        vId = m.data(m.index(self.cmbVehicleNumber.currentIndex(),0))
        sd=ed=y=0
        if(self.cmbYear.currentText()!=''):
            y = int(self.cmbYear.currentText())
        if(y!=0):
            sd = QDateTime(QDate(y,1,1),QTime(0,0,0,1)).toMSecsSinceEpoch()
            ed = QDateTime(QDate(y,12,31),QTime(23,59,59,999)).toMSecsSinceEpoch()
        filterStr = "%s=%d and %s>=%d and %s<%d" %(FN_TF_VEHICLE,vId,FN_TF_DATE,sd,FN_TF_DATE,ed)
        self.tvRecords.model().setFilter(filterStr)
        self.tvRecords.model().select()